import BaseTable from '@/components/BaseTable/usertable';
import type { BaseTableProps } from '@/components/BaseTable/usertable';
import { Button, Input, Select, Space } from 'antd';
import type { TableListItem } from './index';
import type { TableRowSelection } from 'antd/lib/table/interface';
import { useEffect, useState } from 'react';
import RoleForm from './role';
import BaseModal from '@/components/BaseModal';
import useModalState from '@/hook/UseModalState';
import HomeWorkForm from './form';
import { getUser, removeUser, updateUser } from '@/services/ant-design-pro/api';
import usePagination from '@/hook/UsePagination';
import { UserOutlined } from '@ant-design/icons';
import { themeButtonStyle } from '../../../config/globalStyle';
import './style.less';
import { listSchoolAdminUsers, getRoleList, getOrgan } from '@/graphql/queries';
import client from '@/graphql/client';

const schoolId = localStorage.getItem('schoolId');
const RoleSearch = (props: { handleSearch?: (params?: any) => void }) => {
  const [roleOption, setRoleOption] = useState([]);
  const [gradeOption, setGradeOption] = useState([]);
  const [role, setRole] = useState('');
  const [grade, setGrade] = useState('');
  const { handleSearch } = props;
  const [nameValue, setNameValue] = useState('');

  const handlePropsSearch = () => {
    const params = { name: nameValue, role, grade };

    handleSearch!(params);
  };
  const handleChange = (value: string) => {
    console.log(`selected ${value}`);
    setRole(value);
  };
  const handleChangeGrade = (value: string) => {
    console.log(`selected ${value}`);
    setGrade(value);
  };

  useEffect(() => {
    client
      .query({
        query: getRoleList,
        variables: {
          type: 'Role',
        },
      })
      .then((res) => {
        console.log(res);
        const tmp = res.data.nodeList.map((item: any) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
        setRoleOption(tmp);
      });

    client
      .query({
        query: getOrgan,
        variables: {
          id: schoolId,
        },
      })
      .then((res) => {
        const tmp = res.data.node.childOrganList.map((item: any) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
        console.log(tmp);
        setGradeOption(tmp);
      });
  }, []);

  return (
    <>
      <div
        className="RoleSearch"
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          marginBottom: '10px',
        }}
      >
        <div>
          <Space wrap>
            班级:
            <Select
              style={{ width: 200, marginRight: 40 }}
              allowClear
              onChange={handleChangeGrade}
              options={gradeOption}
            />
            姓名:
            <Input
              value={nameValue}
              style={{ width: 200, marginRight: 40 }}
              allowClear
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                if (e.target.value === '') {
                  handleSearch!();
                }
                setNameValue(e.target.value);
              }}
            />
            角色：
            <Select
              style={{ width: 120 }}
              allowClear
              options={roleOption}
              onChange={handleChange}
            />
          </Space>
        </div>
        <div>
          <Button
            onClick={handlePropsSearch}
            style={{
              color: 'rgba(24, 109, 245, 1)',
              backgroundColor: 'rgba(24, 109, 245, 0.1)',
            }}
          >
            查询
          </Button>
        </div>
      </div>
    </>
  );
};

const RoleControl = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleOpen = () => setIsModalOpen(true);
  const handleClose = () => setIsModalOpen(false);
  /** 发布权限分配配置 */
  const releaseProps = {
    title: '权限分配',
    handleOpen,
    handleClose,
    isModalOpen,
    ModalChildren: RoleForm,
  };
  return (
    <div
      style={{
        marginTop: 10,
        marginBottom: 20,
      }}
    >
      <Button icon={<UserOutlined />} onClick={handleOpen} style={themeButtonStyle}>
        权限分配
      </Button>
      <BaseModal {...releaseProps} />
    </div>
  );
};
const Table: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [data, setData] = useState<any>({});
  const [tableListData, setTableListData] = useState<TableListItem[]>([]);
  const { openModal, closeModal, isOpenDelete, isOpenEdit } = useModalState();
  const { currentPage, pageSize, handlePageChange } = usePagination();
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  const fetchUsers = (params?: any) => {
    // setLoading(true);
    // getUser({ current: currentPage, pageSize, ...params }).then((response) => {
    //   console.log(response.data);
    //   // setTableListData(response.data!);
    //   // setTotal(response.total!);
    // });
    //   .finally(() => setLoading(false));
    console.log(params);
    const { role = 'Um9sZToz', name, grade } = params || {};

    client
      .mutate({
        mutation: listSchoolAdminUsers,
        variables: {
          type: 'User',
          organ_id: schoolId,
          expand_organ_user: true,
          role_id: role,
          name,
        },
      })
      .then((res) => {
        console.log(res.data.nodeList);
        const resdata = res.data.nodeList.map((item: any) => {
          return {
            ...item,
            key: item.id,
            phoneNumber: item.phone,
            class:
              item.organs.length === 1
                ? item.organs[0].name
                : item.organs
                    .reduce((a, b) => {
                      // console.log(a, b);
                      // eslint-disable-next-line no-param-reassign
                      return (a += ', ' + b.name);
                    }, '')
                    .slice(1),
            roles:
              item.roles.length === 1
                ? item.roles[0].name
                : item.roles
                    .reduce((a, b) => {
                      // console.log(a, b);
                      // eslint-disable-next-line no-param-reassign
                      return (a += ', ' + b.name);
                    }, '')
                    .slice(1),
          };
        });

        setTableListData(resdata);
        // setTotal(response.total!);
      });
  };

  useEffect(() => {
    fetchUsers();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, pageSize]);

  /** 删除按钮 */
  const handleOpenDeleteModal = (params: any) => {
    openModal('delete');
    setData(params);
  };

  const handleSearch = (params?: any) => {
    fetchUsers(params);
  };

  const handleConfirmDelete = () => {
    removeUser({ data: { key: String(data.key), method: 'delete' } })
      .then((res) => {
        console.log(res);
        fetchUsers();
      })
      .finally(() => {
        closeModal();
      });
  };

  /** 删除信息modal的参数 */
  const deleteInfoProps = {
    type: 'delete',
    info: `是否删除 ${data.name}`,
    isModalOpen: isOpenDelete,
    handleOpenModal: handleOpenDeleteModal,
    handleCloseModal: closeModal,
    handleConfirm: handleConfirmDelete,
  };

  const handleOpenEditModal = (params: any) => {
    openModal('edit');
    setData(params);
  };

  const handleConfirmEdit = (params: any) => {
    console.log(params);
    const dataParams: any = {
      key: Number(data.key),
      method: 'update',
      ...params,
    };
    updateUser({ data: dataParams })
      .then((res) => {
        console.log(res);
        fetchUsers();
      })
      .finally(() => {
        closeModal();
      });
  };

  const editChildProps = {
    initialValues: data,
    handleConfirmEdit,
    closeModal,
  };

  const editInfoProps = {
    title: `编辑 ${data.name}`,
    isModalOpen: isOpenEdit,
    handleOpen: handleOpenEditModal,
    handleClose: closeModal,
    ModalChildren: () => <HomeWorkForm {...editChildProps} />,
    footer: false,
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '手机号',
      dataIndex: 'phoneNumber',
      align: 'center',
    },
    {
      title: '发布者',
      dataIndex: 'roles',
      align: 'center',
    },
    {
      title: '班级',
      dataIndex: 'class',
      align: 'center',
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      render: (text: any, record: any) => [
        <Button key="delete" danger type="link" onClick={() => handleOpenDeleteModal(record)}>
          删除
        </Button>,
        <Button
          key="edit"
          type="link"
          style={{ marginLeft: '10px' }}
          onClick={() => handleOpenEditModal(record)}
        >
          编辑
        </Button>,
      ],
      align: 'center',
    },
  ];

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<TableListItem> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const customPageSize = {
    loading,
    total,
    currentPage,
    pageSize,
    handlePageChange,
  };
  const getTableProps: () => BaseTableProps<TableListItem> = () => ({
    columns,
    dataSource: tableListData,
    rowSelection,
    RoleControl,
    RoleSearch,
    deleteInfoProps,
    editInfoProps,
    customPageSize,
    handleSearch,
  });
  return <BaseTable {...getTableProps()} />;
};
export default Table;
